package CommentPackage;

import Util.DBUtil;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/addComment.do")
public class AddCommentServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        // 获取请求中的参数
        String goodsId = request.getParameter("goods_id");
        String content = request.getParameter("content");
        String user_id = request.getParameter("user_id");
        Integer rating = Integer.valueOf(request.getParameter("rating"));

        System.out.println(user_id);
        System.out.println(goodsId);
        // 数据验证（简单示例，实际应用中应该更严格）
        if (content == null || content.trim().isEmpty()) {
            // 处理错误情况
            response.sendRedirect("errorPage.jsp"); // 或者显示错误消息
            return;
        }

        try (Connection connection = DBUtil.getConnection()) {
            // 插入评论数据到数据库
            String sql = "INSERT INTO comments (goods_id, user_id, content, comment_time, rating) VALUES (?, ?, ?, ?, ?)";
            try (PreparedStatement stmt = connection.prepareStatement(sql)) {
                stmt.setString(1, goodsId);
                stmt.setString(2, user_id);
                stmt.setString(3, content);
                stmt.setTimestamp(4, new java.sql.Timestamp(new Date().getTime()));
                stmt.setInt(5, rating);

                int result = stmt.executeUpdate();
                if (result > 0) {
                    // 插入成功
                    response.sendRedirect("./detail.do?id=" + goodsId); // 重定向回商品详情页
                } else {
                    // 插入失败
                    response.sendRedirect("errorPage.jsp"); // 或者显示错误消息
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException("Adding comment failed", e);
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
